<script setup>
import UserInfo from '@/components/userInfo.vue'
import { ref,reactive } from "vue"
import {addRoleApi,delRoleApi,selectRoleApi,updateRoleApi} from '@/api/admin/role'
import { ElMessage,ElMessageBox } from "element-plus";

function changeValue(e) {
  this.$forceUpdate()
}

//删除角色
const onDel = (roleId)=>{
  ElMessageBox.confirm(
    '确认删除？',
    '警告',
    {
      confirmButtonText:'删除',
      cancelButtonText:'取消',
      type:'warning'
    }
  ).then( async()=>{
    //删除角色
    try{
    const resp = await delRoleApi(roleId)
    if(resp.data.code == 200 ){
      ElMessage.success('删除成功')
      await getRoleList(0)
      return
    }
    }catch(e){
      console.log(e)
      ElMessage.error(e.message)
    }
  }).catch(() => {
  })
}
//浏览角色下的用户
const showViewDialog = ref(false)
const isNull = ref(true)
const userList = ref([])
const onView = (roleId)=>{
  const roles = roleInfo.roleList
  userList.value = []
  roles.forEach(role => {
    if(role.id === roleId){
      showViewDialog.value = true
      userList.value = role.users
      if(role.users.length === 0){
        isNull.value = true
      }else{
        isNull.value = false
      }
    }
  });
}

const roleInfo = reactive({
  roleList:[],
  pageInfo:{}
})
//获取所有角色
getRoleList(0)
async function getRoleList(page){
  try{
    const resp = await selectRoleApi(page)
    if(resp.data.code === 200){
      roleInfo.pageInfo = resp.data.data.page
      if(page === 0){
        roleInfo.roleList = []
      }
      resp.data.data.content.forEach(role =>{
        roleInfo.roleList.push(role)
      })
    }
  }catch(e){
    console.log(e)
  }
}

//更新修改角色
const roleName = ref('')
const roleId = ref(-1)
const showEdit = ref(false)
const onEdit = (id,name)=>{
  showEdit.value = true
  roleName.value = name
  roleId.value = id
}
const roleUpdateForm={
  id:'',
  name:''
}
const roleUpdateFormRef=ref(null)
const roleUpdateFormRulles = {
  name:[
    {
      require:true,
      message:'角色名不能为空',
      trigger:'blur'
    }
  ]
}
function onUpdate() {
  roleUpdateFormRef.value.validate(async(valid)=>{
    if(!valid){
        ElMessage({
            message:'请检查角色名',
            type:'error',
            plain:true
        })
    }
    try{
        roleUpdateForm.id = roleId.value
        const resp  = await updateRoleApi(roleUpdateForm)
        if(resp.data.code === 200){
          showEdit.value=false
          await getRoleList(0)
          ElMessage.success('修改成功')
          location.reload
          roleUpdateFormRef.value.resetFields()
        }
        
    }catch(e){
        console.log(e)
    }
        
  })
}
//添加新角色
const showDialog = ref(false)
const onAddRol = ()=>{
  showDialog.value=true
}
const roleForm = {
  name:''
}
const roleFormRef = ref(null)
const roleFormRules = {
  name:[
    {
      require:true,
      message:'角色名不能为空',
      trigger:'blur'
    }
  ]
}
const confirmAddRole = ()=>{
  roleFormRef.value.validate(async(valid)=>{
    if(roleForm.name === ''){
      ElMessage.warning('角色名不能为空')
      return
    }
    try{
      const resp  = await addRoleApi(roleForm)
      showDialog.value=false
      ElMessage.success('添加成功')
      await getRoleList(0)
      roleFormRef.value.resetFields()
      }catch(e){
      console.log(e)
    } 
  })
}
const cancleAddRole= ()=>{
  showDialog.value = false
}
//获取下一页数据
const getMore = async ()=>{
  if(roleInfo.pageInfo.totalPages === 1 || roleInfo.pageInfo.number >= roleInfo.pageInfo.totalPages){
    return
  }
  getRoleList(roleInfo.pageInfo.number+1)
}
</script>
<template>
    <!-- 添加按钮 -->
    <el-button @click="onAddRol">
      <el-icon><Plus /></el-icon>
    </el-button>
    <!-- 弹出添加role框-->
    <el-dialog 
    title="添加新角色"
    v-model="showDialog">
        <div>
          <el-form 
          ref="roleFormRef"
          :rules="roleFormRules"
          :model="roleForm"
          :inline="true">
            <el-form-item prop="name">
              <el-input 
              @input="changeValue"
              v-model="roleForm.name" 
              placeholder="请输入角色名" 
              clearable></el-input>
            </el-form-item>
          </el-form>
        </div>
        <span class="dialog-footer">
          <el-button 
          type="primary" 
          @click="confirmAddRole">确定</el-button>
          <el-button
          @click="cancleAddRole">取消</el-button>
        </span>
    </el-dialog> 
    <!-- 弹出修改role框 -->
    <el-dialog
    title="修改角色"
    v-model="showEdit"
    >
      <el-form
      ref="roleUpdateFormRef"
      :rules="roleUpdateFormRulles"
      :model="roleUpdateForm"
      :inline="true"
      >
        <el-form-item prop="name">
          <el-input
          v-model="roleUpdateForm.name"
          @input="changeValue"
          :placeholder="roleName"
          clearable>
          </el-input>
        </el-form-item>
      </el-form>
      <span class="dialog-footer">
          <el-button 
          type="primary" 
          @click="onUpdate">修改</el-button>
        </span>
    </el-dialog>
    <!-- 弹出查看role框 -->
    <el-dialog
    title="该标签下的用户："
    v-model="showViewDialog">
      <div 
      class="userInfoCard"
      v-for="userInfo in userList" :key="userInfo.id">
        <!-- user -->
        <UserInfo
          :userInfo="userInfo">
        </UserInfo>
      </div>
       <!-- null 展示 -->
      <div class="class" v-show="isNull">
        该标签下还没有用户呢~
      </div>
    </el-dialog>
    <!-- 角色内容 -->
    <ul 
    :infinite-scroll-distance="20"
    v-infinite-scroll="getMore"
    style="overflow: auto"
    class="role-box">
      <li class="role" v-for="role in roleInfo.roleList" :key="role.id">
        <el-card 
        class="card"
        style="width: 480px" shadow="always">
          <div class="id">角色ID：{{ role.id }}</div>
          <div class="name">角色类型：{{ role.name }}</div>
        
          <!-- 对角色的操作 -->
          <div class="buttons">
            <el-icon 
            @click="onDel(role.id)"
            class="del"><Delete /></el-icon>  
            <el-icon
            class="edit"
            @click="onEdit(role.id,role.name)"><Edit /></el-icon>
            <el-icon
            class="view"
            @click="onView(role.id,role.name)"
            ><View /></el-icon>
          </div>
        </el-card>
      </li>
    </ul>
</template>

<style lang="scss" scoped>
::-webkit-scrollbar{
    display: none;
    background-color: aliceblue;
}


.role-box {
  height: 70vh;
  overflow: scroll;
  list-style-type: none;
  padding: 0;
  margin: 0;
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  gap: 20px;
  background-color: #f5f5f5;
  padding: 20px;
}

.role {
  margin-bottom: 20px;
}

.card {
  border: 1px solid #e0e0e0;
  border-radius: 10px;
  padding: 20px;
  background-color: #fff;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  transition: box-shadow 0.3s ease;

  &:hover {
    box-shadow: 0 8px 16px rgba(0, 0, 0, 0.2);
  }
}

.id {
  font-size: 14px;
  color: #888;
  margin-bottom: 10px;
}

.name {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 20px;
}

.buttons {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.del,
.edit,
.view {
  cursor: pointer;
  color: #409EFF;
  transition: color 0.3s ease;

  &:hover {
    color: #3a8ee6;
  }
}
</style>